﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public sealed class ScrollTool : UnityEngine.UI.ScrollRect {
    private bool m_Moving = false;
    private Vector2 m_Velocity0 = Vector2.zero;
    private Vector3 m_MoveTargetPosition = Vector3.zero;
    private float m_MoveTime = 0.0f;
    public bool isDraging = false; //是否正被拖动
    float halfContent; //滚动界面宽度或高度的一半
    List<ScrollChildBase> arrSkinChildOne = new List<ScrollChildBase> (); //子类列表
    public int count = 0; //数量
    // public string childUrl = "Prefab/UILevelItem";//子类路径，子类需要继承ScrollChildBase
    int toIndex;
    GameObject baseChild; //用于克隆的
    float childHeight; //子类高度
    bool hasInit = false;
    public void init () {
        gameObject.SetActive (true);
        if (this.vertical && this.horizontal) {
            throw new SystemException ("only vertical or horizontal!");
        }
        if (this.horizontal) {
            halfContent = GetComponent<RectTransform> ().rect.width / 2;
        } else {
            halfContent = GetComponent<RectTransform> ().rect.height / 2;
        }
        baseChild = Resources.Load<GameObject> ("Prefab/UILevelItem");
        GameObject _child = Instantiate (baseChild);
        childHeight = _child.GetComponent<RectTransform> ().rect.height;
        Destroy (_child);
    }
    //刷新并添加子类
    public void refresh () {
        if (!hasInit) {
            init ();
            hasInit = true;
        }
        count = Global.GameProxy.arrFileInfo.Count;
        arrSkinChildOne = new List<ScrollChildBase> ();
        for (int i = 0; i < count; i++) {;
            if (content.childCount <= i) {
                GameObject newChild = Instantiate (baseChild);
                newChild.transform.SetParent (content, false);
            }
            Transform child = content.GetChild (i);
            child.gameObject.SetActive (true);
            child.localPosition = new Vector3 (0, -childHeight * (i + 0.5f), 0);
            ScrollChildBase com = child.GetComponent<ScrollChildBase> ();
            arrSkinChildOne.Add (com);
            com.init (i, this);
        }
        for (int i = count; i < content.childCount; i++) {
            Transform child = content.GetChild (i);
            child.gameObject.SetActive (false);
        }
        content.GetComponent<RectTransform> ().SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, childHeight * count);
    }
    public void scrollToIndex (int index, float num) {
        if (this.horizontal) {
            ScrollByOffset (Mathf.Max (0, content.GetChild (index).localPosition.x - halfContent), num); //居中
        } else {
            Transform childOne = content.GetChild (index);
            ScrollByOffset (Mathf.Max (0, -(childOne.localPosition.y)), num); //头顶上边界
        }
    }
    void Update () {
        if (m_Moving) {
            float speed = vertical ? m_Velocity0.y : m_Velocity0.x;
            // Move our position a step closer to the target.
            float step = speed * Time.deltaTime; // calculate distance to move
            content.localPosition = Vector3.MoveTowards (content.localPosition, m_MoveTargetPosition, step);
            // Check if the position of the cube and sphere are approximately equal.
            if (Vector3.Distance (content.localPosition, m_MoveTargetPosition) < 0.001f) {
                m_Moving = false;
            }
            m_MoveTime = m_MoveTime - Time.deltaTime;
            if (m_MoveTime <= 0.0f) {
                m_Moving = false;
            }
        }
    }
    //
    public void ScrollByOffset (float offset, float time) {
        var contentTF = content.transform;
        if (vertical) {
            if (time < 0.001f) {
                content.localPosition = new Vector3 (contentTF.localPosition.x, offset, contentTF.localPosition.z);
                return;
            }
            float ds = offset - contentTF.localPosition.y;
            if (Mathf.Abs (ds) < 0.001f) {
                m_Moving = false;
            } else {
                var speed = Mathf.Abs (ds / time);
                m_Moving = true;
                m_Velocity0.y = speed;
                m_MoveTargetPosition = new Vector3 (contentTF.localPosition.x, offset, contentTF.localPosition.z);
                m_MoveTime = time;
            }
        } else {
            if (time < 0.001f) {
                content.localPosition = new Vector3 (offset, contentTF.localPosition.y, contentTF.localPosition.z);
                return;
            }
            float ds = offset + contentTF.localPosition.x;
            if (Mathf.Abs (ds) < 0.001f) {
                m_Moving = false;
            } else {
                var speed = Mathf.Abs (ds / time);
                m_Moving = true;
                m_Velocity0.x = speed;
                m_MoveTargetPosition = new Vector3 (-offset, contentTF.localPosition.y, contentTF.localPosition.z);
                m_MoveTime = time;
            }
        }
    }
    //数度固定的滚动方法
    public void _ScrollByOffset (float offset, float time = 999) {
        var contentTF = content.transform;
        if (vertical) {
            if (time < 0.001f) {
                content.localPosition = new Vector3 (contentTF.localPosition.x, offset, contentTF.localPosition.z);
                return;
            }
            float ds = offset - contentTF.localPosition.y;
            if (Mathf.Abs (ds) < 0.001f) {
                m_Moving = false;
            } else {
                var speed = 150;
                m_Moving = true;
                m_Velocity0.y = speed;
                m_MoveTargetPosition = new Vector3 (contentTF.localPosition.x, offset, contentTF.localPosition.z);
                m_MoveTime = time;
            }
        } else {
            if (time < 0.001f) {
                content.localPosition = new Vector3 (offset, contentTF.localPosition.y, contentTF.localPosition.z);
                return;
            }
            float ds = offset + contentTF.localPosition.x;
            if (Mathf.Abs (ds) < 0.001f) {
                m_Moving = false;
            } else {
                var speed = 150;
                m_Moving = true;
                m_Velocity0.x = speed;
                m_MoveTargetPosition = new Vector3 (-offset, contentTF.localPosition.y, contentTF.localPosition.z);
                m_MoveTime = time;
            }
        }
    }
    public override void OnEndDrag (PointerEventData eventData) {
        base.OnEndDrag (eventData);
        isDraging = false;
    }

    public override void OnDrag (PointerEventData eventData) {
        base.OnDrag (eventData);
        isDraging = true;
    }
    //需要拖动到事件上
    public void OnValueChanged () {
        if (!isDraging) {
            ScrollToCurrent ();
        }
        // arrSkinChildOne.ForEach (one => {
        //     one.refreshScale (getScale (one.transform, 0.5f));
        // });
    }
    //自动滚动到对应位置//目前只做了横滚
    public void ScrollToCurrent () {
        float x = content.localPosition.x; //0 - 负很多
        float d = 9999;
        int index = 0;
        for (int i = 0; i < content.childCount; i++) {
            float _d = Mathf.Abs (content.GetChild (i).localPosition.x - halfContent + x);
            if (_d < d) {
                d = _d;
                index = i;
            }
        }
        _ScrollByOffset (Mathf.Max (0, content.GetChild (index).localPosition.x - halfContent));;
    }
    //返回滚动时的缩放//最大缩放默认是1，就是最中间的//哎，先这样
    public float getScale (Transform child, float min = 0.33f) {
        float x = content.localPosition.x;
        float d = Mathf.Abs (child.localPosition.x - halfContent + x);
        float scale = (1 - d / halfContent);
        return Mathf.Max (min, scale);
    }
}